<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加标签"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="edit-tag-container">
      <!-- 已选标签区域 -->
      <div class="selected-tags-section">
        <div class="section-title">
          <span>已选标签：</span>
        </div>
        <div class="selected-tags-list">
          <el-tag
            v-for="tag in selectedTags"
            :key="tag.id"
            :color="tag.color"
            style="color: #ffffff; border: none; font-weight: 500; margin-right: 8px; margin-bottom: 8px;"
            closable
            @close="removeSelectedTag(tag.id)"
            class="selected-tag-item"
          >
            {{ tag.name }}
          </el-tag>
          <div v-if="selectedTags.length === 0" class="empty-tip">
            暂无标签
          </div>
        </div>
      </div>

      <!-- 标签选择区域 -->
      <div class="tag-selection-section">
        <el-container class="tag-selection-container">
          <!-- 左侧分类菜单 -->
          <el-aside width="160px" class="category-aside">
            <el-menu
              :default-active="activeCategory?.id?.toString()"
              class="category-menu"
              mode="vertical"
              @select="handleMenuSelect"
            >
              <el-menu-item
                v-for="category in categories"
                :key="category.id"
                :index="category.id.toString()"
              >
                {{ category.name }}
              </el-menu-item>
            </el-menu>
          </el-aside>

          <!-- 右侧标签内容区 -->
          <el-main class="tag-main-content">
            <div v-if="activeCategory" class="content-container">
              <!-- 分类标题和搜索 -->
              <div class="content-header">
                <h3 class="category-title">{{ activeCategory.name }}</h3>
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索标签"
                  clearable
                  style="width: 200px;"
                >
                  <template #prefix>
                    <Icon icon="ep:search" />
                  </template>
                </el-input>
              </div>

              <!-- 二级分类和标签 -->
              <div 
                v-for="subCategory in currentSubCategories" 
                :key="subCategory.id"
                class="sub-category-section"
              >
                <!-- 二级分类标题 -->
                <el-divider content-position="left">
                  <span style="color: #606266; font-size: 14px;">{{ subCategory.name }}</span>
                </el-divider>

                <!-- 该二级分类下的标签 -->
                <div class="tags-grid" v-loading="loading">
                  <el-tag
                    v-for="tag in getTagsBySubCategory(subCategory.id)"
                    :key="tag.id"
                    :color="tag.color"
                    :class="['selectable-tag', { selected: isTagSelected(tag.id) }]"
                    style="color: #ffffff; border: none; font-weight: 500; margin: 4px; transition: all 0.2s ease;"
                    @click="toggleTag(tag)"
                  >
                    {{ tag.name }}
                  </el-tag>
                  <div v-if="getTagsBySubCategory(subCategory.id).length === 0 && !loading" class="empty-tip">
                    暂无标签数据
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-content">
              <el-empty description="请选择一个分类" />
            </div>
          </el-main>
        </el-container>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { Tag } from '@/api/localLife/spu'
import * as TagApi from '@/api/system/tags'
import * as TagCategoryApi from '@/api/system/tags/category'
import * as SpuApi from '@/api/mall/product/spu'

type UserTag = Tag

interface TagCategory {
  id: number
  name: string
}

interface TagSubCategory {
  id: number
  name: string
  categoryId: number
}

const props = defineProps<{
  currentTags: UserTag[]
  spuId?: number // 商品SPU ID，用于更新商品标签
}>()

const emit = defineEmits<{
  success: [tags: UserTag[]]
}>()

const message = useMessage()

const dialogVisible = ref(false)
const selectedTags = ref<UserTag[]>([])
const searchKeyword = ref('')
const loading = ref(false)

// 真实标签数据
const allTags = ref<UserTag[]>([])

// 动态分类数据（从API获取）
const categories = ref<TagCategory[]>([])
const subCategories = ref<TagSubCategory[]>([])
const activeCategory = ref<TagCategory>()

/** 加载标签数据 */
const loadTags = async () => {
  try {
    loading.value = true
    
    // 并行获取标签分类和标签数据
    const [categoryResult, tagResult] = await Promise.all([
      TagCategoryApi.getTagCategoryList({}),
      TagApi.getTagList()
    ])
    
    // 处理分类数据
    const categoryList = Array.isArray(categoryResult) ? categoryResult : (categoryResult.data || [])
    // 处理标签数据
    const tagList = Array.isArray(tagResult) ? tagResult : (tagResult.data || [])
    
    // 生成随机颜色
    const colors = [
      '#FF6B6B', '#4ECDC4', '#45B7D1', '#F7DC6F', '#BB8FCE', '#85C1E9',
      '#82E0AA', '#F8C471', '#E74C3C', '#9B59B6', '#3498DB', '#1ABC9C',
      '#F39C12', '#8E44AD', '#27AE60', '#FF5722', '#9C27B0', '#673AB7',
      '#3F51B5', '#2196F3', '#03DAC6', '#4CAF50', '#795548', '#607D8B',
      '#424242', '#8BC34A', '#CDDC39', '#FFC107', '#FF69B4', '#DC143C',
      '#4169E1', '#FF4500', '#8B4513', '#32CD32'
    ]
    
    // 构建分类映射
    const categoryMap = new Map<number, { name: string, parentId: number }>()
    categoryList.forEach(category => {
      categoryMap.set(category.id, {
        name: category.name,
        parentId: category.parentId
      })
    })
    
    // 按categoryId分组标签，构建分类结构
    const tagsByCategory = new Map<number, any[]>()
    
    tagList.forEach((tag, index) => {
      const categoryId = tag.categoryId || 1
      const categoryInfo = categoryMap.get(categoryId)
      const categoryName = categoryInfo?.name || `分类${categoryId}`
      
      if (!tagsByCategory.has(categoryId)) {
        tagsByCategory.set(categoryId, [])
      }
      
      tagsByCategory.get(categoryId)!.push({
        id: tag.id,
        name: tag.name,
        color: colors[index % colors.length],
        categoryId: categoryId,
        subCategoryId: categoryId, // 简化：使用categoryId作为subCategoryId
        categoryName: categoryName,
        subCategoryName: categoryName
      })
    })
    
    // 构建一级分类（parentId为0或null的分类）
    const rootCategories = categoryList.filter(cat => !cat.parentId || cat.parentId === 0)
    categories.value = rootCategories.map(cat => ({
      id: cat.id,
      name: cat.name
    }))
    
    // 构建二级分类（有parentId的分类）
    const childCategories = categoryList.filter(cat => cat.parentId && cat.parentId !== 0)
    subCategories.value = childCategories.map(cat => ({
      id: cat.id,
      name: cat.name,
      categoryId: cat.parentId
    }))
    
    // 如果没有二级分类，将一级分类也作为二级分类
    if (subCategories.value.length === 0) {
      subCategories.value = categories.value.map(cat => ({
        id: cat.id,
        name: cat.name,
        categoryId: cat.id
      }))
    }
    
    // 构建所有标签数据
    allTags.value = Array.from(tagsByCategory.values()).flat()
    
  } catch (error) {
    console.error('加载标签失败:', error)
    message.error('加载标签失败')
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  selectedTags.value = [...props.currentTags]
  await loadTags()
  // 默认选择第一个分类
  if (categories.value.length > 0) {
    selectCategory(categories.value[0])
  }
}

/** 选择分类 */
const selectCategory = (category: TagCategory) => {
  activeCategory.value = category
  searchKeyword.value = '' // 清空搜索
}

/** 菜单选择处理 */
const handleMenuSelect = (index: string) => {
  const categoryId = parseInt(index)
  const category = categories.value.find(c => c.id === categoryId)
  if (category) {
    selectCategory(category)
  }
}

/** 获取当前一级分类下的二级分类 */
const currentSubCategories = computed(() => {
  if (!activeCategory.value) return []
  return subCategories.value.filter(sub => sub.categoryId === activeCategory.value!.id)
})

/** 根据二级分类ID获取标签 */
const getTagsBySubCategory = (subCategoryId: number) => {
  let tags = allTags.value.filter(tag => tag.subCategoryId === subCategoryId)
  
  // 搜索过滤
  if (searchKeyword.value) {
    tags = tags.filter(tag => 
      tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  return tags
}

/** 检查标签是否已选择 */
const isTagSelected = (tagId: number) => {
  // 根据标签名称判断是否已选中
  const currentTag = allTags.value.find(tag => tag.id === tagId)
  if (!currentTag) return false
  return selectedTags.value.some(tag => tag.name === currentTag.name)
}

/** 切换标签选择状态 */
const toggleTag = (tag: UserTag) => {
  // 根据标签名称查找是否已选中
  const index = selectedTags.value.findIndex(t => t.name === tag.name)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
}

/** 移除已选标签 */
const removeSelectedTag = (tagId: number) => {
  // 根据标签名称移除
  const tagToRemove = selectedTags.value.find(tag => tag.id === tagId)
  if (tagToRemove) {
    const index = selectedTags.value.findIndex(tag => tag.name === tagToRemove.name)
    if (index > -1) {
      selectedTags.value.splice(index, 1)
    }
  }
}

/** 确认提交 */
const handleConfirm = async () => {
  try {
    // 如果有spuId，调用商品更新接口
    if (props.spuId) {
      const tags = selectedTags.value.map(tag => tag.name)
      await SpuApi.updateSpu({
        id: props.spuId,
        tags: tags
      })
      message.success('商品标签更新成功')
    }
    
    emit('success', selectedTags.value)
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败，请重试')
  }
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.edit-tag-container {
  .selected-tags-section {
    margin-bottom: 20px;
    
    .section-title {
      margin-bottom: 12px;
      font-weight: 500;
      color: #303133;
    }
    
    .selected-tags-list {
      min-height: 40px;
      padding: 8px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fafafa;
      
      .empty-tip {
        color: #909399;
        font-size: 14px;
        line-height: 24px;
      }
      
      .selected-tag-item {
        :deep(.el-tag__close) {
          color: #ffffff !important;
          
          &:hover {
            color: #ffffff !important;
            background-color: rgba(255, 255, 255, 0.2) !important;
          }
        }
      }
    }
  }
  
  .tag-selection-section {
    .tag-selection-container {
      border: 1px solid var(--el-border-color);
      border-radius: var(--el-border-radius-base);
      overflow: hidden;
      height: 500px;
      
      .category-aside {
        border-right: 1px solid var(--el-border-color);
        
        .category-menu {
          border-right: none;
          height: 100%;
          
          :deep(.el-menu-item) {
            height: auto;
            padding: 16px 20px;
            line-height: 1.5;
          }
        }
      }
      
      .tag-main-content {
        padding: 0;
        
        .content-container {
          padding: 20px;
          height: 500px;
          overflow-y: auto;
          
          .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            
            .category-title {
              margin: 0;
              font-size: 18px;
              font-weight: 600;
              color: var(--el-text-color-primary);
            }
          }
          
          .sub-category-section {
            margin-bottom: 24px;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
          
                      .tags-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 16px;
            
            .selectable-tag {
              cursor: pointer;
              position: relative;
              
              &.selected {
                &::after {
                  content: '✓';
                  position: absolute;
                  top: -8px;
                  right: -8px;
                  width: 16px;
                  height: 16px;
                  background-color: var(--el-color-primary);
                  color: white;
                  border-radius: 50%;
                  font-size: 10px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-weight: bold;
                }
              }
            }
            
            .empty-tip {
              color: #909399;
              font-size: 14px;
              line-height: 24px;
              width: 100%;
              text-align: center;
              padding: 20px 0;
            }
          }
        }
        
        .empty-content {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 500px;
        }
      }
    }
  }
}
</style> 
